<template>
    <view class="content">
        <van-nav-bar :title="scrolling? navBarTitle : '' " left-arrow @click-left="onClickLeft"></van-nav-bar>
        <scroll-view class="scroll-content" scroll-y :lower-threshold="80" @scroll="scrollPage" show-scrollbar="false">
            <view class="pageTop">
                <view class="cartAd">
                    <view class="cartAd_title">{{ navBarTitle }}</view>
                </view>
            </view>
            <view class="middle">
                <form @submit="formSubmit" @reset="formReset">
                    <view class="formItem">
                        <view class="formItemName">头像</view>
                        <view class="box_top_detail_left">
                            <button class="info_img" plain open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                                <image class="avatar" mode="aspectFill" :src="userInfo.avatarUrl ? userInfo.avatarUrl:defaultAvatar" style="width: 80rpx;height: 80rpx; "> </image>
                            </button>
                        </view>
                    </view>
                    <!-- <van-cell title="发票类型" value="普通发票-电子" is-link></van-cell> -->
                    <view class="formItem">
                        <view class="formItemName">昵称</view>
                        <view class="formItemContent text">
                            <input type="nickname" class="weui-input" placeholder="请填写昵称" :value="userInfo.nickName" @change="onChangeNickName" />
                        </view>
                    </view>
                    <view class="formItem">
                        <view class="formItemName">性别</view>
                        <view class="formItemContent text" @click="selectSexAndBirthday(0)">{{ userInfo.gender==1? '男' : (  userInfo.gender==0?'女':'未设置')}}
                        </view>
                    </view>
                    <view class="formItem">
                        <view class="formItemName">生日</view>
                        <view class="formItemContent text" @click="selectSexAndBirthday(1)">{{!userInfo.birthday  ? '未设置' : userInfo.birthday}}
                        </view>
                    </view>
                    <view class="formItem">
                        <view class="formItemName">地址</view>
                        <view class="formItemContent text" @click="selectAddress">{{!userInfo.userAddress ? '未设置' : userInfo.userAddress }} </view>
                    </view>
                    <view class="formItem">
                        <view class="formItemName">绑定电话</view>
                        <view class="formItemContent text" @click="selectTel">{{!userInfo.phone  ? '未设置' : userInfo.phone }} </view>
                    </view>
                    <view class="formItem">
                        <view class="formItemName">客服电话</view>
                        <view class="formItemContent text" @click="onClickPhone">{{serviceTelephone}} </view>
                    </view>
                    <!-- <van-cell-group inset> -->
                    <!-- <van-cell :border="false" title="发票抬头" value="填写需要开发票的企业" is-link></van-cell> -->

                </form>
            </view>
        </scroll-view>
        <view class="bottom">
            <view class="btnArea">
                <van-button type="primary"  @click="logOut">退出登录</van-button>
            </view>

            <!-- <view class="no-login" v-html="textWithLink" @click="writeOff"> </view> -->
            <!-- <view class="no-login" ><rich-text :nodes="richTextData"></rich-text> </view> -->
             <view class="no-login">
                <span class="underline-view" @tap="underlineClicked">注销账号</span>
                <span>，注销后无法恢复，请谨慎操作</span>
             </view>
        </view>

        <sexPopup :show="showSex" :symbol="symbol" :paramsInfo="item" @closePopup="closePopup" @submitCurrentDate="submitCurrentDate"></sexPopup>
    </view>
</template>
<script>
import CryptoJS from 'crypto-js'; // 确保已正确导入 CryptoJS

import {weixinLogoutApi} from '@/api/login'
import {getWxUserInfoApi,updateUserInfoApi} from '@/api/mine'
import sexPopup from '@/mycomponents/sexPopup.vue';
const defaultAvatarUrl = 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/defaultAvatar.png'

export default {

    components: {
        sexPopup
    },

    data () {
        return {
            navBarTitle: '个人信息',
            scrolling: false,
            showSex:false,

            columns: [
                { text: '男', value: 'male',index:0 },
                { text: '女', value: 'female',index:1 }
            ],
            defaultAvatar:defaultAvatarUrl,
            userInfo:{
                avatarUrl:defaultAvatarUrl,
                nickName:'张新萍',
                gender:'未设置',
                birthday:'未设置',
                userAddress:'盐湖区滨湖一号3单元2号楼201',
                phone:'15582991226',
                selectedSex:'未设置',
            },
            gender:0,
            serviceTelephone:'19703596555',
            symbol:'',//标志
            item:'',
            textWithLink:'<a href="#" style="text-decoration-color:red">注销账号</a> ，注销后无法恢复，请谨慎操作',
            richTextData:'<span>这是一段文字，<u style="text-decoration-color:red" @tap="underlineClicked">这几个字</u>有下划线并且可以点击。</span>',
            updateParams:{ id:'', }

        }
    },
    // underlineClicked () {
    //         console.log("下划线文字被点击了");
    //     },
    computed: {},

    watch: {},
    onLoad () {
        const userInfo=uni.getStorageSync('userInfo')
        if(userInfo){
            this.userInfo=userInfo

        }
    },
    onReady () {
       this.getWxUserInfo()
    },

    methods: {
        // 滑动
        scrollPage (e) {
            console.log(e.detail.scrollTop, this.scrolling)
            if (e.detail.scrollTop > 25 && !this.scrolling) {
                this.scrolling = true
            } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
                this.scrolling = false
            }
        },
        // 返回键
        onClickLeft () {
            uni.navigateBack()
        },
        underlineClicked () {
            console.log("下划线文字被点击了");
            uni.navigateTo({
                url:'/pages/profile/closeAccount'
            })
        },
		// 获取用户头像
		async onChooseAvatar(e) {
			console.log(e,'获取头像',e.detail.avatarUrl)
        
            try {
                uni.showLoading({ title: '上传中...' });
                // const res = await uni.chooseImage({
                //     count: 1,
                //     sizeType: ['compressed'],
                //     sourceType: ['album', 'camera']
                // });
                // console.log('选择的图片路径:', res);
                // const filePath = res.tempFilePaths[0];
                // const fileType = res.tempFiles[0].type;

                const filePath = e.detail.avatarUrl;
                const fileType = e.type;
                 // 先压缩图片
                const compressedPath = await new Promise((resolve, reject) => {
                    uni.compressImage({
                        src: filePath,
                        quality: 80, // 质量压缩到80%
                        width: '50px', // 宽度压缩到300px
                        height: '50px', // 添加高度参数保持比例
                        compressType: 'scale', // 使用缩放模式而非裁剪  
                        success: res => {
                            console.log('压缩成功', res); // 添加日志
                            resolve(res.tempFilePath); // 修改为 tempFilePath
                        },
                        fail: err => {
                            console.error('压缩失败', err); // 添加错误日志
                            reject(new Error('图片压缩失败'))
                        }
                    });
                });


                const ossUrl = await this.uploadToOSS({
                    tempFilePath: compressedPath,
                    path: compressedPath,
                    type: fileType
                });

                // const finalUrl = `${ossUrl}?x-oss-process=image/resize,w_300/quality,q_80`;
                 const finalUrl = ossUrl;
                console.log('最终的图片URL:', finalUrl);
                this.userInfo.avatarUrl = finalUrl;
                this.updateParams.avatarUrl = finalUrl;
                await this.updateUserInfo(this.updateParams);

            } catch (error) {
                console.error('Avatar upload failed:', error);
                uni.showToast({
                    title: error.message || '头像上传失败',
                    icon: 'none'
                });
            } finally {
                uni.hideLoading();
            }
         
		},

        // 上传图片到阿里云
        async uploadToOSS(file) {
            console.log('开始上传文件:', file);
            const OSS_CONFIG = {
                region: 'oss-cn-beijing',
                accessKeyId: 'LTAI5t977yzTgy3KuHsZpNGp',
                accessKeySecret: '3XClQa1PDAqqHyK1avhz5npkhN7Uel',
                bucket: '17lelife-bucket',
                host: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/',
                dir: 'WeChat-App-Picture/userAvatarUrl/'
            };
            try {
                // 强化文件路径校验
                const fileRealPath = file.tempFilePath || file.path || file.url;
                if (!fileRealPath) {
                    throw new Error('无法获取有效文件路径，请重新选择文件');
                }

                // 安全获取文件扩展名
                const getExtension = () => {
                    return file.type?.split('/')[1] ||
                        file.name?.split('.').pop() ||
                        fileRealPath.split('.').pop() ||
                        'jpg';
                };

                // 生成唯一文件名
                const fileName = `${Date.now()}_${Math.random()
                    .toString(36)
                    .substr(2, 12)}.${getExtension().toLowerCase()}`;
                const filePath = `${OSS_CONFIG.dir}${fileName}`;

                // 生成安全策略
                const generatePolicy = () => {
                    const policy = {
                        expiration: new Date(Date.now() + 3600000).toISOString(),
                        conditions: [
                            ["content-length-range", 0, 10485760], // 10MB限制
                            ["starts-with", "$key", OSS_CONFIG.dir]
                        ]
                    };
                    return CryptoJS.enc.Base64.stringify(
                        CryptoJS.enc.Utf8.parse(JSON.stringify(policy))
                    );
                };

                // 生成签名
                const policy = generatePolicy();
                const signature = CryptoJS.HmacSHA1(policy, OSS_CONFIG.accessKeySecret)
                    .toString(CryptoJS.enc.Base64);

                // 执行上传
                const uploadResult = await new Promise((resolve, reject) => {
                    uni.uploadFile({
                        url: OSS_CONFIG.host,
                        filePath: fileRealPath,
                        name: 'file',
                        formData: {
                            key: filePath,
                            policy: policy,
                            OSSAccessKeyId: OSS_CONFIG.accessKeyId,
                            signature: signature,
                            success_action_status: '200'
                        },
                        success: (res) => {
                            if (res.statusCode === 200) {
                                resolve(`${OSS_CONFIG.host}${filePath}`);
                            } else {
                                reject(new Error(`上传失败，状态码：${res.statusCode}`));
                            }
                        },
                        fail: (err) => {
                            reject(new Error(`上传请求失败：${err.errMsg}`));
                        }
                    });
                });

                return uploadResult;
            } catch (error) {
                console.error('OSS上传失败详情:', {
                    error,
                    fileObject: file,
                    pathAttempts: {
                        tempFilePath: typeof file === 'object' ? file.tempFilePath : undefined,
                        path: typeof file === 'object' ? file.path : undefined,
                        url: typeof file === 'object' ? file.url : undefined
                    }
                });
                throw new Error(`文件上传失败：${error.message}`);
            }
        },

        // 获取用户昵称
		onChangeNickName(e){
			console.log(e,'获取昵称')
			this.userInfo.nickName=e.detail.value
            console.log(this.userInfo.nickName,'获取昵称')
            this.updateParams.nickName = e.detail.value
            if(!this.userInfo.nickName){
                return false
            }
            this.updateUserInfo(this.updateParams)
		},

        // 显示性别弹窗
        selectSexAndBirthday(val){
            switch(val){
                case 0:
                    this.symbol='sex'
                    this.item=this.userInfo.gendar
                    break;
                case 1:
                    this.symbol='birthday'
                    this.item=this.userInfo.birthday
                break;
            }
            this.showSex=true
        },

        // 管理地址
        selectAddress(){
            const params={}
            uni.navigateTo({
                url:'/pages/address/myAddress?params=' +
                encodeURIComponent(JSON.stringify(params))
            })
        },

        // 关闭性别
        closePopup(sign,item){
            this.showSex=false
        },

        // 确认性别 生日
        submitCurrentDate(item){
            console.log(item,'提交信息')
            this.closePopup()
            switch (this.symbol) {
                case 'sex':
                    this.userInfo.selectedSex = item
                    this.updateParams.gender=item=='女'?0:1
                    break;
                case 'birthday':
                    this.userInfo.selectedBirth = item
                    this.updateParams.birthday=item
                    break;
            }

            this.updateUserInfo(this.updateParams)

        },

        // 确认
        formSubmit(e) {
            console.log('form发生了submit事件，携带数据为：', e)
            // Toast.success('编辑地址成功')
            uni.setStorage({
				key: 'userInfo',
				data: this.userInfo
			})
            
        },
        formReset(e) {
            console.log('form发生了submit事件，携带数据为：', e.detail.value)
            // Toast.success('编辑地址成功')
            
        },

        // 设置电话
        selectTel(){
            uni.navigateTo({
                // url:'/pages/profile/setTel'
            })
        },
        // 获取用户信息
        getWxUserInfo(){
            getWxUserInfoApi().then(res=>{
                if(res.code === 200){
                    const data = res?.data || {}
                    const addressList = res.data?.ebUserAddressList || [];
                    console.log(data.gender,'gender')
                    // this.userInfo = {
                    //     ...data,
                    //     userAddress: addressList.length > 0 ?
                    //         addressList[0]?.detail :
                    //         '暂未设置地址'
                    // };
                    // debugger
                    this.userInfo = {
                        id: data.id,
                        avatarUrl: data.avatarUrl? data.avatarUrl:defaultAvatarUrl,
                        nickName: data.nickName ? data.nickName: '微信用户',
                        gender: data.gender,
                        birthday: data?.birthday || '未设置', // 使用更明确的默认值
                        phone: data?.phone || '未设置',
                        userAddress: addressList.length > 0 ? addressList[0]?.detail : '暂未设置地址',
                        hasSelfPickupInfo:data.hasSelfPickupInfo,
                    };

                    uni.setStorage({
                        key: 'userInfo',
                        data: this.userInfo
                    });
                    console.log(this.userInfo.gender,'获取用户信息',this.userInfo.gender==1? '男' : ( this.userInfo.gender==0?'女':'未设置') )
                    this.updateParams = { id: this.userInfo.id, }
                }
            }).catch(err=>{
                console.log(err,'获取用户信息失败')
            })
        },

        // 新增地址格式化方法
        formatAddress(address) {
            if (!address) return '';
            return [address.provinceName, address.cityName, address.districtName, address.detail].filter(Boolean).join('');
        },
        // 退出登录
        logOut(){
            const params={
                token:uni.getStorageSync('access_token')
            }
            weixinLogoutApi().then(res=>{
                console.log(res,'res')
                uni.removeStorageSync('access_token')
                uni.removeStorageSync('userInfo')
                uni.removeStorageSync('refresh_token')

                // 跳转到登录页或首页
                uni.reLaunch({
                    url: '/pages/my/mine'
                });
            }).catch(err => {
                console.error('退出登录失败:', err);
            })

        },
        // 注销
        writeOff(){
            console.log('oooooooo')
        },

        // 更新用户信息
        updateUserInfo(params){
            console.log(params,'更新用户信息')
            updateUserInfoApi(params).then(res => {
                if (res.code == 200) {
                    uni.setStorage({
                        key: 'userInfo',
                        data: this.userInfo
                    })
                    this.getWxUserInfo()
                } else {
                    uni.showToast({
                        title: res.message,
                        icon: 'none',
                        duration: 2000
                    })
                }
            })	
        }
    }

}
</script>
<style lang="scss" scoped>
// @import '@/styles/variables.scss';

.content {
    background-color: #ffffff;
    display: flex;
    flex-direction:column;
    overflow:hidden;
    box-sizing: border-box;
    height:100vh;
}
.scroll-content {
    flex: 1;
    height: 1px;
}

.pageTop{
    // display: flex;
    // flex-direction: column;
    // background-color: #f9f9f9;
    // padding-bottom: 3px;
}

 // 页面标题部分
 .cartAd {
    background-color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 17px 24px 21px 24px ;

}

.cartAd_title {
    font-size: 30px;
    text-align: left;
    line-height: 30px;
    color: #111111;
}
.orderBox{
    background-color: #ffffff;
    display: flex;
    align-items: center;
    padding: 23px 24px 21px 24px ;
}

.goodsPic{
    width: 15%;
    img{
        width: 100%;
        height: auto;
    }
}
.pageTopRight{
    margin-left:15px;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
}


.middle{
    padding:24px 24px 120px 24px;
}
.formItem{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100rpx;
}
.formItemName{
    color: #111111;
    font-size: 26rpx;
    line-height: 26rpx;
}
.box_top_detail_left {
    display: flex;
    align-items: center;

    .info_img {
        position: relative;
        width: 84rpx;
        height: 84rpx;
        background-color: rgb(255, 255, 255, 0.5) !important;
        border-radius: 50%;
        border: none !important;
        padding: 0px !important;
        border-radius: 50px;

        image {
            position: absolute;
            border-radius: 50px;
            left: 1rpx;
            top: 1rpx;
        }
    }

    .info_name {
        margin-top: 34rpx;
        margin-left: 30rpx;
        margin-bottom: 42rpx;
        font-weight: bolder;
        font-size: 38rpx;
        text-align: left;
        color: #111111;
        line-height: 38rpx;
    }

    // 登录注册
    .register {
        font-size: 38rpx;
        text-align: left;
        color: #111111;
        line-height: 38rpx;
    }

    .weui-input {
        margin-left: 30rpx;
    }
}
.formItemContent{
    font-size: 26rpx;
    color: #666666;
}
.text{
    color: #666666;
    text-align: right;
    min-width: 80rpx;
}

.tips{
    border-radius: 4rpx;
    background: #f9f9f9;
    padding: 16rpx 18rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 28rpx;
    color: #111111;
}
.tipsLeft{

}

::v-deep .van-nav-bar__left {
    width: 56px;
    height: 44px;
}

::v-deep .van-icon {
    color: #242629 !important;
}


button{
    border: none !important;
}
button[plain]{
    border: none !important;
}
.bottom{
    position: fixed;
    bottom: 0;
    width: calc(100% - 96rpx);
    padding-left: 48rpx;
    padding-right: 48rpx;
    padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
}
::v-deep .van-button--primary {
    width: 100%;
    height: 86rpx;
    border-radius: 38rpx;
    background: #FF6203 !important;
    border: 1px solid #ff6203 !important;
    font-size: 28rpx !important;
    line-height: 86rpx;
}
.no-login{
    font-size: 26rpx;
    // line-height: 26rpx;
    // margin-bottom: calc(81rpx + env(safe-area-inset-bottom));
    // height: 44px;
    // line-height: 24rpx;
    color: #757980;
    text-align: center;
    margin-top: 52rpx;
}
.b30{
    margin-bottom: 30px;
}
.underline-view {
    // text-decoration: underline;
    // color: inherit;
    cursor: pointer;
    position: relative;

    &::after {
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        bottom: -4rpx;
        border-bottom: 1rpx solid #757980;;
    }
}
</style>
